import MSLogger; log = MSLogger.get('wsgi_server')
import MSEvent
import MSDatetime
import datetime
import time
import urllib

class Reader:
    def __init__(self, MSAPIUrl):
        self.MSUrl = MSAPIUrl

    def getName(self): return '(MSAPI)'

    def readURLData(self, request, skey, timerange):
        url = self.MSUrl + '/do?data=%s&skey=%s&begin=%s&end=%s' % (request,
                                                                    skey,
                                                                    timerange[0],
                                                                    timerange[1])
        try:
            log.debug('readURLData:: %s', url)
            f = urllib.urlopen(url)
            d = f.readlines()
            if len(d) == 0:
                return None
            return d
        except Exception, err:
            log.error('ReaderMSAPI::readURLData: %s', str(err))
            return []

    def normalizeDatetime(self, d):
        return d.strftime(MSDatetime.TIME_FORMAT_MAGIC_API)
    def normalizeTimerange(self, timerange):
        return (self.normalizeDatetime(timerange[0]), self.normalizeDatetime(timerange[1]))

    def parseEvent(self, estring):
        s = estring.split('/>')[0]
        s = s.split('<')[1]
        s = s.split(' ')
        e = {}
        for prop in s[1:len(s)]:
            prop = prop.split('=')
            e[prop[0]] = prop[1].replace('"', '')
        return e

#common face
    def getEvents_PGSM_TIMED(self, obj, timerange):
        events = []
        eventsPGSM  = self.readURLData('events', obj.storage.meta['skey'], timerange)
        if eventsPGSM:
            for s in eventsPGSM:
                try:
                    e = MSEvent.Event()
                    e.fromPGSM(self.parseEvent(s))
                    events.append(e)
                except Exception, err:
                    log.error('getEvents_PGSM::%s', str(err))
                    continue
        if len(events) > 0: obj.append(events, True)
        return len(events)

    def getEvents_ContactId_TIMED(self, obj, timerange):
        events = []
        eventsCONTACTID = self.readURLData('contactId', obj.storage.meta['skey'], timerange)
        if eventsCONTACTID:
            for s in eventsCONTACTID:
                try:
                    e = MSEvent.Event()
                    e.fromContactId(self.parseEvent(s))
                    events.append(e)
                except Exception, err:
                    log.error('getEvents_ContactId::%s', str(err))
                    continue
        if len(events) > 0: obj.append(events, True)
        return len(events)

    def getEvents_TODAY(self, obj):
        timerange   = self.normalizeTimerange(MSDatetime.getToday())
        num =   self.getEvents_PGSM_TIMED(obj, timerange)
        num +=  self.getEvents_ContactId_TIMED(obj, timerange)
        return num

    def getEvents_TIMED(self, obj, starttime):
        timerange = self.normalizeTimerange(MSDatetime.getToday())
        timerange = (self.normalizeDatetime(starttime), timerange[1])
        num =   self.getEvents_PGSM_TIMED(obj, timerange)
        num +=  self.getEvents_ContactId_TIMED(obj, timerange)
        #self.getEvents_Bolid_TIMED(obj, timerange)
        #self.getEvents_GPS_TIMED(obj, timerange)
        return num


##########################
if __name__ == "__main__":
    import sys
    import MSObject

    if len(sys.argv) != 2: print "Usage: %s <storage_root>" % (sys.argv[0])
    g_root = sys.argv[1]

    def case1():
        f1 = MSObject.MSFile.File(g_root, 'test_obj')
        f1.destroy()

        o1 = MSObject.MSObject(g_root, 'test_obj')
        o1.open()
        o1.storage.meta['msId'] = 1
        o1.storage.meta['skey'] = 'a3049a3c320553AC361f668a6bF339' 
        o1.flush()

    def case2():
        o = MSObject.MSObject(g_root, 'test_obj')
        o.open()
        if o.storage.txn != 1: raise RuntimeError('case2: failed 1')
        if o.storage.meta['msId'] != 1: raise RuntimeError('case2: failed 2')

        reader = Reader()
        reader.getEvents(o)

    case1()
    case2()
